package com.qboot.core.config;

import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.qboot.system.entity.SysPermission;
import com.qboot.system.entity.SysRole;
import com.qboot.system.service.SysUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 授权、认证
 *
 * @author Tellsea
 * @date 2022/11/25
 */
@Component
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class RolePermissionConfig implements StpInterface {

    private final SysUserService sysUserService;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        if (StpUtil.hasRole("admin")) {
            return Arrays.asList("*:*:*");
        }
        List<SysPermission> permissionList = sysUserService.listPermissionById(Long.parseLong(String.valueOf(StpUtil.getLoginId())));
        if (!CollectionUtils.isEmpty(permissionList) && !Objects.isNull(permissionList.get(0))) {
            return permissionList.stream().map(SysPermission::getPerms).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<SysRole> roleList = sysUserService.listRoleById(Long.parseLong(String.valueOf(StpUtil.getLoginId())));
        if (!CollectionUtils.isEmpty(roleList) && !Objects.isNull(roleList.get(0))) {
            return roleList.stream().map(SysRole::getRoleKey).collect(Collectors.toList());
        }
        return Collections.emptyList();
    }
}
